// 全局变量
let currentUser = null;
let currentPage = 1;
let currentPostId = null;

// API 基础URL
const API_BASE = '/api/v1';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    checkAuthStatus();
    loadMyPosts();
});

// 检查认证状态
function checkAuthStatus() {
    const token = localStorage.getItem('token');
    if (token) {
        // 验证token有效性
        fetch(`${API_BASE}/auth/profile`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Token无效');
            }
        })
        .then(data => {
            currentUser = data.user;
            updateUserDisplay();
        })
        .catch(error => {
            localStorage.removeItem('token');
            window.location.href = '/';
        });
    } else {
        window.location.href = '/';
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const messageEl = document.getElementById('message');
    messageEl.textContent = message;
    messageEl.className = `message ${type}`;
    messageEl.classList.add('show');
    
    setTimeout(() => {
        messageEl.classList.remove('show');
    }, 3000);
}

// 显示加载状态
function showLoading() {
    document.getElementById('loading').style.display = 'block';
}

// 隐藏加载状态
function hideLoading() {
    document.getElementById('loading').style.display = 'none';
}

// 隐藏所有表单
function hideAllForms() {
    const forms = ['createPostForm', 'editPostForm'];
    forms.forEach(id => {
        document.getElementById(id).style.display = 'none';
    });
    document.getElementById('postsList').style.display = 'block';
}

// 显示创建文章表单
function showCreatePost() {
    document.getElementById('postsList').style.display = 'none';
    document.getElementById('createPostForm').style.display = 'block';
    // 清空表单
    document.getElementById('postTitle').value = '';
    document.getElementById('postContent').value = '';
}

// 隐藏创建文章表单
function hideCreatePost() {
    hideAllForms();
}

// 隐藏编辑文章表单
function hideEditPost() {
    hideAllForms();
}

// 更新用户显示
function updateUserDisplay() {
    const userInfo = document.getElementById('userInfo');
    const currentUsername = document.getElementById('currentUsername');
    
    if (currentUser && currentUser.username) {
        userInfo.style.display = 'inline';
        currentUsername.textContent = currentUser.username;
    } else {
        userInfo.style.display = 'none';
        currentUsername.textContent = '';
    }
}

// 用户退出
function logout() {
    localStorage.removeItem('token');
    currentUser = null;
    window.location.href = '/';
}

// 加载我的文章
function loadMyPosts(page = 1) {
    currentPage = page;
    showLoading();
    
    const token = localStorage.getItem('token');
    fetch(`${API_BASE}/my-posts?page=${page}&limit=10`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.posts) {
            displayPosts(data.posts, 'postsContent');
            displayPagination(data.pagination, 'pagination');
        } else {
            showMessage(data.error || '加载失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('加载失败: ' + error.message, 'error');
    });
}

// 显示文章列表（完全复制首页逻辑，添加编辑删除按钮）
function displayPosts(posts, containerId) {
    const container = document.getElementById(containerId);
    
    if (!posts || posts.length === 0) {
        container.innerHTML = '<div class="no-posts">暂无文章</div>';
        return;
    }
    
    container.innerHTML = posts.map(post => `
        <div class="post-item fade-in">
            <h3 class="post-title">${post.title}</h3>
            <div class="post-meta">
                <span><i class="fas fa-user"></i> ${post.user.username}</span>
                <span><i class="fas fa-calendar"></i> ${new Date(post.created_at).toLocaleDateString('zh-CN')}</span>
                <span id="commentCount-${post.id}"><i class="fas fa-comments"></i> <span id="commentCountText-${post.id}">0</span> 评论</span>
            </div>
            <div class="post-content">${post.content.replace(/\n/g, '<br>')}</div>
            
            <!-- 编辑删除按钮 -->
            <div class="post-actions" style="margin-top: 15px;">
                <button class="btn btn-small btn-secondary" onclick="editPost(${post.id})">编辑</button>
                <button class="btn btn-small btn-danger" onclick="deletePost(${post.id})">删除</button>
            </div>
            
            <!-- 评论按钮 -->
            <div class="comment-actions" style="margin-top: 15px;">
                <button class="btn btn-primary btn-small" onclick="toggleComments(${post.id})" id="commentBtn-${post.id}">
                    <i class="fas fa-comment"></i> 查看评论
                </button>
                <button class="btn btn-secondary btn-small" onclick="toggleCommentForm(${post.id})" id="writeCommentBtn-${post.id}">
                    <i class="fas fa-edit"></i> 写评论
                </button>
            </div>
            
            <!-- 评论表单 -->
            <div id="commentForm-${post.id}" class="comment-form" style="display: none; margin-top: 15px;">
                <form onsubmit="submitComment(event, ${post.id})">
                    <div class="form-group">
                        <textarea id="commentContent-${post.id}" placeholder="写下你的评论..." rows="3" required maxlength="500" oninput="updateCharCount(${post.id})"></textarea>
                        <div style="text-align: right; margin-top: 5px; color: #666; font-size: 0.9rem;">
                            <span id="charCount-${post.id}">0</span>/500
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-small">发表评论</button>
                    <button type="button" class="btn btn-secondary btn-small" onclick="toggleCommentForm(${post.id})">取消</button>
                </form>
            </div>
            
            <!-- 评论列表 -->
            <div id="commentsList-${post.id}" class="comments-list" style="display: none; margin-top: 15px;">
            </div>
        </div>
    `).join('');

    // 延迟加载评论数
    setTimeout(() => {
        posts.forEach(post => {
            loadCommentCount(post.id);
        });
    }, 100);
}

// 显示分页
function displayPagination(pagination, containerId) {
    const container = document.getElementById(containerId);
    
    if (!pagination || pagination.total_pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let paginationHTML = '<div class="pagination-controls">';
    
    // 上一页
    if (pagination.current_page > 1) {
        paginationHTML += `<button class="btn btn-secondary btn-small" onclick="loadMyPosts(${pagination.current_page - 1})">上一页</button>`;
    }
    
    // 页码
    for (let i = 1; i <= pagination.total_pages; i++) {
        if (i === pagination.current_page) {
            paginationHTML += `<button class="btn btn-primary btn-small active">${i}</button>`;
        } else {
            paginationHTML += `<button class="btn btn-secondary btn-small" onclick="loadMyPosts(${i})">${i}</button>`;
        }
    }
    
    // 下一页
    if (pagination.current_page < pagination.total_pages) {
        paginationHTML += `<button class="btn btn-secondary btn-small" onclick="loadMyPosts(${pagination.current_page + 1})">下一页</button>`;
    }
    
    paginationHTML += '</div>';
    container.innerHTML = paginationHTML;
}

// 加载评论数量
function loadCommentCount(postId) {
    fetch(`${API_BASE}/comments/post/${postId}`)
    .then(response => response.json())
    .then(data => {
        if (data.comments) {
            const countElement = document.getElementById(`commentCountText-${postId}`);
            if (countElement) {
                countElement.textContent = data.pagination.total;
            }
        }
    })
    .catch(error => {
        console.error('加载评论数失败:', error);
    });
}

// 切换评论列表显示
function toggleComments(postId) {
    const commentsList = document.getElementById(`commentsList-${postId}`);
    const isHidden = commentsList.style.display === 'none' || commentsList.style.display === '';
    
    if (isHidden) {
        commentsList.style.display = 'block';
        loadCommentsForPost(postId);
    } else {
        commentsList.style.display = 'none';
    }
}

// 切换评论表单显示
function toggleCommentForm(postId) {
    if (!currentUser) {
        showMessage('请先登录后发表评论', 'error');
        return;
    }
    
    const commentForm = document.getElementById(`commentForm-${postId}`);
    const isHidden = commentForm.style.display === 'none' || commentForm.style.display === '';
    
    if (isHidden) {
        commentForm.style.display = 'block';
        const textarea = document.getElementById(`commentContent-${postId}`);
        if (textarea) {
            textarea.focus();
        }
    } else {
        commentForm.style.display = 'none';
    }
}

// 加载文章评论
function loadCommentsForPost(postId) {
    fetch(`${API_BASE}/comments/post/${postId}`)
    .then(response => response.json())
    .then(data => {
        if (data.comments) {
            displayComments(data.comments, postId);
        }
    })
    .catch(error => {
        console.error('加载评论失败:', error);
    });
}

// 显示评论列表
function displayComments(comments, postId) {
    const container = document.getElementById(`commentsList-${postId}`);
    
    if (!comments || comments.length === 0) {
        container.innerHTML = '<div class="no-comments">暂无评论</div>';
        return;
    }
    
    container.innerHTML = comments.map(comment => `
        <div class="comment-item">
            <div class="comment-meta">
                <span><i class="fas fa-user"></i> ${comment.user.username}</span>
                <span><i class="fas fa-calendar"></i> ${new Date(comment.created_at).toLocaleDateString('zh-CN')}</span>
                ${currentUser && comment.user_id === currentUser.id ? `
                    <button class="btn btn-danger btn-small comment-delete" onclick="deleteComment(${comment.id}, ${postId})">删除</button>
                ` : ''}
            </div>
            <div class="comment-content">${comment.content.replace(/\n/g, '<br>')}</div>
        </div>
    `).join('');
}

// 更新字符计数
function updateCharCount(postId) {
    const textarea = document.getElementById(`commentContent-${postId}`);
    const charCount = document.getElementById(`charCount-${postId}`);
    
    if (textarea && charCount) {
        charCount.textContent = textarea.value.length;
    }
}

// 提交评论
function submitComment(event, postId) {
    event.preventDefault();
    
    if (!currentUser) {
        showMessage('请先登录', 'error');
        return;
    }
    
    const content = document.getElementById(`commentContent-${postId}`).value.trim();
    if (!content) {
        showMessage('请输入评论内容', 'error');
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/comments`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            post_id: postId,
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            // 清空表单
            document.getElementById(`commentContent-${postId}`).value = '';
            document.getElementById(`charCount-${postId}`).textContent = '0';
            // 隐藏表单
            toggleCommentForm(postId);
            // 重新加载评论
            loadCommentsForPost(postId);
            // 更新评论数
            loadCommentCount(postId);
        } else {
            showMessage(data.error || '发表评论失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('发表评论失败: ' + error.message, 'error');
    });
}

// 删除评论
function deleteComment(commentId, postId) {
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/comments/${commentId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            // 重新加载评论
            loadCommentsForPost(postId);
            // 更新评论数
            loadCommentCount(postId);
        } else {
            showMessage(data.error || '删除评论失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('删除评论失败: ' + error.message, 'error');
    });
}

// 创建文章
function createPost(event) {
    event.preventDefault();
    
    const title = document.getElementById('postTitle').value.trim();
    const content = document.getElementById('postContent').value.trim();
    
    if (!title || !content) {
        showMessage('请填写标题和内容', 'error');
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/posts`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ title, content })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            hideCreatePost();
            loadMyPosts();
        } else {
            showMessage(data.error || '发布失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('发布失败: ' + error.message, 'error');
    });
}

// 编辑文章
function editPost(postId) {
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/posts/${postId}`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.post) {
            document.getElementById('editPostId').value = data.post.id;
            document.getElementById('editPostTitle').value = data.post.title;
            document.getElementById('editPostContent').value = data.post.content;
            
            document.getElementById('postsList').style.display = 'none';
            document.getElementById('editPostForm').style.display = 'block';
        } else {
            showMessage(data.error || '获取文章失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('获取文章失败: ' + error.message, 'error');
    });
}

// 更新文章
function updatePost(event) {
    event.preventDefault();
    
    const postId = document.getElementById('editPostId').value;
    const title = document.getElementById('editPostTitle').value.trim();
    const content = document.getElementById('editPostContent').value.trim();
    
    if (!title || !content) {
        showMessage('请填写标题和内容', 'error');
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/posts/${postId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ title, content })
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            hideEditPost();
            loadMyPosts();
        } else {
            showMessage(data.error || '更新失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('更新失败: ' + error.message, 'error');
    });
}

// 删除文章
function deletePost(postId) {
    if (!confirm('确定要删除这篇文章吗？删除后无法恢复！')) {
        return;
    }
    
    const token = localStorage.getItem('token');
    showLoading();
    
    fetch(`${API_BASE}/posts/${postId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        hideLoading();
        if (data.message) {
            showMessage(data.message, 'success');
            loadMyPosts();
        } else {
            showMessage(data.error || '删除失败', 'error');
        }
    })
    .catch(error => {
        hideLoading();
        showMessage('删除失败: ' + error.message, 'error');
    });
}
